package edu.mama.college.aspect;

import edu.mama.college.model.JsonResult;
import edu.mama.college.model.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
@Slf4j
public class ControllerAccessAspect {

    /**
     * 拦截AccountController类的方法，仅限已登录用户调用
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("execution(public * edu.mama.college.controller.AccountController.*(..)) || execution(public * edu.mama.college.controller.UserCourseController.getUserCourse(..))")
    public Object loginRequired(ProceedingJoinPoint pjp) throws Throwable {
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            //未登录
            return JsonResult.fail("用户未登录");

        } else {
            //已登录
            return pjp.proceed();
        }
    }

    /**
     * TODO 拦截admin包下的controller方法，仅限管理员调用
     */
    @Around("execution(public * edu.mama.college.controller.admin.*.*(..))")
    public Object isAdmin(ProceedingJoinPoint pjp) throws Throwable {
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        User user = (User) request.getSession().getAttribute("user");

        if (user == null) {
            //未登录
            return JsonResult.fail("用户未登录");
        }else if( !"ADMIN".equals(user.getRole())){
            return JsonResult.fail("没有权限");
        } else {
            //已登录
            return pjp.proceed();
        }
    }
}
